<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=0,shrink-to-fit=no, viewport-fit=cover">
    <meta name="keywords" content="蓝桥到家">
    <meta name="description" itemprop="description" content="生鲜副食、饮品乳品、鲜花蛋糕">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>注册</title>
    <link rel="stylesheet" type="text/css" href="../styles/reset.css" />
    <link rel="stylesheet" type="text/css" href="../styles/login.css">
    <link rel="stylesheet" type="text/css" href="../styles/common.css" />
    <script src="../js/common.js"></script>
    <script src="../js/zepto.min.js"></script>
    <style>
        .error-tip {
            color: #ff4d4f;
            font-size: 12px;
            margin: -10px 0 15px 70px;
            display: none;
        }
        
        /* 获取验证码按钮样式 */
        .code {
            background-color: #165DFF;
            transition: background-color 0.3s;
        }
        .code span {
            color: white;
        }
        
        .code.disabled {
            background-color: white;
            border: 1px solid #ddd;
            pointer-events: none;
        }
        .code.disabled span {
            color: #999;
        }
        
        #regCode {
            color: #000 !important;
            caret-color: #000;
        }
        #regCode::placeholder {
            color: #ccc;
        }
    </style>
</head>

<body>
    <div class="wrap">
        <div class="container">
            <!-- logo start-->
            <div class="header_logo">
                <img src="https://static.shiyanlou.com/lanqiao/frontend/dist/img/lanqiao-logo.1bbdf85.svg" />
            </div>
            <!-- logo end -->
            
            <!-- 注册 start-->
            <div class="login_item">
                <span class="login_text">手机号</span>
                <input class="login_input" type="tel" maxlength="11" placeholder="输入手机号" id="regPhone"/>
            </div>
            <p class="error-tip" id="regPhoneError">请输入正确的手机号</p>
            
            <div class="login_item">
                <span class="login_text">验证码</span>
                <div class="auth_div">
                    <input class="login_input" type="text" maxlength="4" placeholder="输入验证码" id="regCode"/>
                    <div class="code" id="regGetCodeBtn">
                        <span>获取验证码</span>
                    </div>
                </div>
            </div>
            <p class="error-tip" id="regCodeError">验证码错误</p>
            
            <div class="login_item">
                <span class="login_text">密码</span>
                <input class="login_input" type="password" maxlength="12" placeholder="设置6-12位登录密码" id="regPwd"/>
            </div>
            <p class="error-tip" id="regPwdError">请输入6-12位密码</p>
            
            <div class="login_button">
                <a href="javascript:;" id="regBtn"><span>注册</span></a>
            </div>
            <div class="register_div">
                <a href="login.html" class="register_text">已有账号，请登录</a>
            </div>
            <!-- 注册 end-->
        </div>
    </div>
    <script>
        // 从URL获取手机号（如果有）
        function getUrlParam(name) {
            const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
            const r = window.location.search.substr(1).match(reg);
            return r ? decodeURIComponent(r[2]) : '';
        }

        // 从API获取用户信息（替换localStorage）
        async function getUsers() {
            try {
                const response = await fetch('http://127.0.0.1:8090/users');
                if (!response.ok) {
                    throw new Error('获取用户信息失败');
                }
                return await response.json();
            } catch (error) {
                console.error('获取用户列表错误:', error);
                alert('无法连接到服务器，请稍后再试');
                return [];
            }
        }

        // 将新用户信息存入API（替换localStorage）
        async function saveUser(user) {
            try {
                const response = await fetch('http://127.0.0.1:8090/users', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(user)
                });
                if (!response.ok) {
                    throw new Error('保存用户信息失败');
                }
                return await response.json();
            } catch (error) {
                console.error('保存用户错误:', error);
                alert('注册失败，请稍后再试');
                throw error; // 抛出错误以便调用者处理
            }
        }

        // 验证手机号
        function isPhoneValid(phone) {
            const reg = /^1[3-9]\d{9}$/;
            return reg.test(phone);
        }

        // 页面加载时填充手机号
        $(function() {
            const phone = getUrlParam('phone');
            if (phone) {
                $('#regPhone').val(phone);
            }
        });

        // 获取注册验证码
        $('#regGetCodeBtn').click(async function() {
            const phone = $('#regPhone').val().trim();
            
            // 验证手机号格式
            if (!isPhoneValid(phone)) {
                $('#regPhoneError').show();
                return;
            }
            $('#regPhoneError').hide();

            // 检查手机号是否已注册（从API获取用户列表）
            const users = await getUsers();
            if (users.some(u => u.phone === phone)) {
                alert('该手机号已注册，可直接登录');
                $(this).removeClass('disabled');
                return;
            }

            // 点击后按钮变为白色（倒计时）
            const $btn = $(this).addClass('disabled');
            let count = 60;
            const timer = setInterval(() => {
                $btn.find('span').text(`${count}s后重新获取`);
                count--;
                if (count < 0) {
                    clearInterval(timer);
                    $btn.removeClass('disabled').find('span').text('获取验证码');
                }
            }, 1000);

            // 自动填充验证码1234
            setTimeout(() => {
                $('#regCode').val('1234');
            }, 300);
        });

        // 注册按钮点击事件
        $('#regBtn').click(async function() {
            const phone = $('#regPhone').val().trim();
            const code = $('#regCode').val().trim();
            const pwd = $('#regPwd').val().trim();
            let isValid = true;

            // 验证手机号
            if (!isPhoneValid(phone)) {
                $('#regPhoneError').show();
                isValid = false;
            } else {
                $('#regPhoneError').hide();
            }

            // 验证验证码
            if (code !== '1234') {
                $('#regCodeError').show();
                isValid = false;
            } else {
                $('#regCodeError').hide();
            }

            // 验证密码
            if (pwd.length < 6 || pwd.length > 12) {
                $('#regPwdError').show();
                isValid = false;
            } else {
                $('#regPwdError').hide();
            }

            // 所有验证通过
            if (isValid) {
                // 获取用户列表检查是否已注册
                const users = await getUsers();
                const existingUser = users.find(u => u.phone === phone);

                if (existingUser) {
                    // 用户已存在，直接登录（保存登录状态并跳转）
                    sessionStorage.setItem('currentUser', JSON.stringify(existingUser));
                    alert('用户已存在，自动登录成功');
                    window.location.href = 'index.html'; // 替换为实际登录后跳转的页面
                } else {
                    // 注册新用户
                    await saveUser({ phone, password: pwd });
                    alert('注册成功，即将跳转到登录页');
                    window.location.href = `login.html?phone=${phone}`;
                }
            }
        });

        // 输入时隐藏错误提示
        $('.login_input').on('input', function() {
            $(this).closest('.login_item').next('.error-tip').hide();
        });
    </script>
</body>
</html>